//
//  CirclReplyViewController.swift
//  Gaoloumi
//
//  Created by Jasper on 4/3/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import UITableView_FDTemplateLayoutCell
import MJRefresh
import SVProgressHUD
import AVOSCloud

class CirclReplyViewController: RootViewController, UITableViewDelegate, UITableViewDataSource, ReplySubTableViewCellDelegate {
    
    var topic: Topic?
    var city: City?
    var replyArray = [Reply]()
    
    var orderType = 0 // 默认正序
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView.tableFooterView = UIView()
        
        let segment = UISegmentedControl(items: ["正序查看", "倒序查看"])
        segment.selectedSegmentIndex = orderType
        segment.setTitleTextAttributes([NSFontAttributeName: UIFont.systemFont(ofSize: 14)], for: UIControlState())
        segment.addTarget(self, action: #selector(CirclReplyViewController.segmentClicked(_:)), for: .valueChanged)
        navigationItem.titleView = segment
        
        NotificationCenter.default.addObserver(self, selector: #selector(CirclReplyViewController.refreshData(_:)), name: NSNotification.Name(rawValue: kNotificationRefreshReplyListView), object: nil)
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {
            self.rquestData(true)
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {
            self.rquestData(false)
        })
        self.rquestData(true)
        
        // 每次进来点击数自动加1
        topic!.incrementKey(kTopicKeyClickCount)
        topic!.fetchWhenSave = true
        topic!.saveInBackground()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    func segmentClicked(_ segment: UISegmentedControl) {
        if orderType == segment.selectedSegmentIndex {
            return
        }
        orderType = segment.selectedSegmentIndex
        replyArray.removeAll()
        rquestData(true)
        //        tableView.scrollToTop()
    }
    
    func refreshData(_ noti: Notification) {
        self.rquestData(true)
    }
    
    func rquestData(_ header: Bool) {
        SVProgressHUD.show()
        let query: AVQuery = Reply.query()
        query.includeKey(kReplyKeyUser)
        query.includeKey(kReplyKeyContentImage)
        query.includeKey(kReplyKeyReply)
        //        query.includeKey(kReplyKeyUser)
        query.whereKey(kReplyKeyTopic, equalTo: topic)
        if orderType == 0 {
            query.order(byAscending: "updatedAt")
        } else {
            query.order(byDescending: "updatedAt")
        }
        
        query.limit = kNetPageSize
        if !header {
            let top = replyArray.last
            let date = top?.object(forKey: "updatedAt")
            if date != nil {
                if orderType == 0 {
                    query.whereKey("updatedAt", greaterThan: date)
                } else {
                    query.whereKey("updatedAt", lessThan: date)
                }
            }
        }
        
        query.findObjectsInBackground { (objects: [Any]?, error: Error?) in
            
            if error == nil && objects != nil {
                if let reply = objects as? [Reply] {
                    if header {
                        self.replyArray.removeAll()
                    }
                    self.replyArray += reply
                    self.tableView.reloadData()
                    SVProgressHUD.dismiss()
                } else {
                    SVProgressHUD.showError(withStatus: "获取列表失败")
                }
            } else {
                SVProgressHUD.showError(withStatus: error?.localizedDescription);
            }
            self.tableView.mj_header.endRefreshing()
            if objects != nil && (objects?.count)! < kNetPageSize {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            } else {
                if header {
                    self.tableView.mj_footer.resetNoMoreData()
                } else {
                    self.tableView.mj_footer.endRefreshing()
                }
            }
        }
    }
    
    // MARK: UITableViewDelegate
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return CGFloat.leastNormalMagnitude
        }
        return 10
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else {
            return replyArray.count
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (indexPath as NSIndexPath).section == 0 {
            return tableView.fd_heightForCell(withIdentifier: "ReplyMainTableViewCell", configuration: { (cell: Any?) in
                let mainCell = cell as? ReplyMainTableViewCell
                mainCell!.refreshView(self.topic!)
            })
        } else {
            return tableView.fd_heightForCell(withIdentifier: "ReplySubTableViewCell", configuration: { (cell: Any?) in
                let mainCell = cell as? ReplySubTableViewCell
                mainCell!.refreshView(self.replyArray[(indexPath as NSIndexPath).row], topic: self.topic!, lou: (indexPath as NSIndexPath).row)
            })
        }
    }
    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if (indexPath as NSIndexPath).section == 0 {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ReplyMainTableViewCell", for: indexPath) as! ReplyMainTableViewCell
            cell.selectionStyle = .none
            cell.refreshView(topic!)
            return cell
        } else {
            let cell = tableView.dequeueReusableCell(withIdentifier: "ReplySubTableViewCell", for: indexPath) as! ReplySubTableViewCell
            cell.delegate = self
            cell.tag = (indexPath as NSIndexPath).row
            cell.selectionStyle = .none
            
            var lou = (indexPath as NSIndexPath).row
            if orderType == 1 { //逆序
                lou = (topic?.replyCount)! - (indexPath as NSIndexPath).row - 1
            }
            
            cell.refreshView(self.replyArray[(indexPath as NSIndexPath).row], topic: self.topic!, lou: lou)
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        if (indexPath as NSIndexPath).section == 0 {
            return // 主楼不弹出
        }
        replyAction((indexPath as NSIndexPath).row)
    }
    
    @IBAction func replyButtonClicked(_ sender: UIBarButtonItem) {
        
        let alertController = UIAlertController(title: "楼主", message: "", preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        alertController.addAction(cancelAction)
        
        let confirmAction = UIAlertAction(title: "回复", style: .destructive, handler: { (action) in
            self.toReplyController(true)
        })
        let reportAction = UIAlertAction(title: "举报", style: .destructive, handler: { (action) in
            let subalertController = UIAlertController(title: "举报楼主?", message: "", preferredStyle: .actionSheet)
            let subcancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            
            let handle = { (action:UIAlertAction) in
                let top = self.topic
                top!.isReported = true;
                top!.saveInBackground({ (succed: Bool, error: Error?) in
                    SVProgressHUD.showSuccess(withStatus: "谢谢支持，我们会尽快处理您的举报哦~")
                })
            }
            
            let action1 = UIAlertAction(title: "广告信息", style: .destructive, handler: handle)
            let action2 = UIAlertAction(title: "情色话题", style: .destructive, handler: handle)
            let action3 = UIAlertAction(title: "人身攻击", style: .destructive, handler: handle)
            let action4 = UIAlertAction(title: "无关内容", style: .destructive, handler: handle)
            
            subalertController.addAction(action1)
            subalertController.addAction(action2)
            subalertController.addAction(action3)
            subalertController.addAction(action4)
            subalertController.addAction(subcancelAction)
            self.present(subalertController, animated: true, completion: nil)
        })
        alertController.addAction(confirmAction)
        alertController.addAction(reportAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    // ReplySubTableViewCellDelegate
    
    func replySubTableViewCellReplyClick(_ cellRow: Int) {
        replyAction(cellRow)
    }
    
    func replyAction(_ cellRow: Int) {
        let alertController = UIAlertController(title: "\(cellRow+1)楼", message: "", preferredStyle: .actionSheet)
        let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        alertController.addAction(cancelAction)
        
        let confirmAction = UIAlertAction(title: "回复", style: .destructive, handler: { (action) in
            self.toReplyController(false, row: cellRow)
        })
        let reportAction = UIAlertAction(title: "举报", style: .destructive, handler: { (action) in
            let subalertController = UIAlertController(title: "举报\(cellRow+1)楼?", message: "", preferredStyle: .actionSheet)
            let subcancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
            
            let handle = { (action:UIAlertAction) in
                let reply = self.replyArray[cellRow]
                reply.isReported = true;
                reply.saveInBackground({ (succed: Bool, error: Error?) in
                    SVProgressHUD.showSuccess(withStatus: "谢谢支持，我们会尽快处理您的举报哦~")
                })
            }
            
            let action1 = UIAlertAction(title: "广告信息", style: .destructive, handler: handle)
            let action2 = UIAlertAction(title: "情色话题", style: .destructive, handler: handle)
            let action3 = UIAlertAction(title: "人身攻击", style: .destructive, handler: handle)
            let action4 = UIAlertAction(title: "无关内容", style: .destructive, handler: handle)
            
            subalertController.addAction(action1)
            subalertController.addAction(action2)
            subalertController.addAction(action3)
            subalertController.addAction(action4)
            subalertController.addAction(subcancelAction)
            self.present(subalertController, animated: true, completion: nil)
        })
        alertController.addAction(confirmAction)
        alertController.addAction(reportAction)
        self.present(alertController, animated: true, completion: nil)
    }
    
    func toReplyController(_ islou:Bool, row: Int = 0) {
        if AVUser.current() == nil { // 没登录
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let loginViewController = storyboard.instantiateViewController(withIdentifier: "LoginViewController");
            self.navigationController?.pushViewController(loginViewController, animated: true)
        } else {
            let storyboard = UIStoryboard(name: "Main", bundle: nil);
            let replyTopVC = storyboard.instantiateViewController(withIdentifier: "ReplyTopViewController") as! ReplyTopViewController;
            replyTopVC.city = city
            replyTopVC.topic = topic
            if !islou {
                replyTopVC.louNum = row
                replyTopVC.mainReply = replyArray[row]
            }
            self.navigationController?.pushViewController(replyTopVC, animated: true)
        }
    }
}
